package xdu.lz.stage5_jucUtils.chapter5_lock.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created at 2019/10/19 0019 下午 8:40
 */
public class ReentrantLockApi {

    /**
     * ReentrantLock特有的API
     *
     * 1、lock()  不能被打断
     * 2、lockInterruptibly()  允许被打断
     * 3、tryLock();尝试获取，立马返回，返回boolean
     * 4、tryLock(time,timeUnit);  最多等待time，也允许被打断
     * 5、unlock();
     * 6、Condition condition = lock.newCondition();后面讲
     */
    private static final ReentrantLock lock = new ReentrantLock();


    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> lock());
        t1.start();
        Thread.sleep(200);
        Thread t2 = new Thread(() -> lock());
        t2.start();
        Thread.sleep(200);

        System.out.println("hasQueuedThreads = " + lock.hasQueuedThreads());
        System.out.println("getQueueLength = " + lock.getQueueLength());
        System.out.println("hasQueuedThread-t2 :"+lock.hasQueuedThread(t2));

        //the number of holds on this lock by the current thread:当前线程拿到锁的数量
        //当前线程是mian，当然输出是0
        System.out.println("getHoldCount ="+lock.getHoldCount());

        System.out.println("the lock is Locked ="+lock.isLocked());
    }

    public static void lock(){
        try {
            //这个方法不可被中断
            //     lock.lock();
            //这个方法会被中断
            lock.lockInterruptibly();
            System.out.println(Thread.currentThread().getName()+" get the lock");
            System.out.println(Thread.currentThread().getName() + " getHoldCount ="+lock
                    .getHoldCount());
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getName()+" release the lock");
        }
    }

}
